package com.mdlib.helper.ui.fragments.home;

import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ljlib.core.base.BaseFragment;
import com.ljlib.core.util.LogUtil;
import com.ljlib.core.util.common.TimeUtils;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.common.MDConstant;
import com.mdlib.helper.event.CityEvnet;
import com.mdlib.helper.event.LocationEvent;
import com.mdlib.helper.model.AccountModel;
import com.mdlib.helper.model.AppModel;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.model.entity.BannerEntity;
import com.mdlib.helper.model.entity.MessageEntity;
import com.mdlib.helper.model.entity.OrderEntity;
import com.mdlib.helper.model.entity.RunInfo;
import com.mdlib.helper.model.entity.RunSystemMessage;
import com.mdlib.helper.model.entity.StatusEntity;
import com.mdlib.helper.model.entity.WebViewEntity;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.ui.widget.springview.HelperHeads;
import com.mdlib.helper.ui.widget.springview.SpringView;
import com.mdlib.helper.ui.widget.text.LJAdverView;
import com.mdlib.helper.ui.widget.text.LJViewAdapter;
import com.mdlib.helper.utils.ToastUtil;
import com.mdlib.helper.utils.bga.BGABanner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 作者：HQY on 16/11/9 16:58
 * 邮箱：hqy_xz@126.com
 */

public class RushHomeFragment extends BaseFragment {


    private final String ROLE = "2";

    @Bind(R.id.banner_rush_carousel)
    BGABanner mBannerRushCarousel;

    @Bind(R.id.ll_home_location)
    LinearLayout mLlHomeLocation;
    @Bind(R.id.ll_home_refresh)
    LinearLayout mLlHomeRefresh;
    @Bind(R.id.ll_home_vicinity)
    LinearLayout mLlHomeVicinity;
    @Bind(R.id.tv_rush_order)
    TextView mTvRushOrder;
    @Bind(R.id.tv_rush_vicinity_order)
    TextView mTvRushVicinityOrder;
    @Bind(R.id.tv_system_message)
    TextView mTvSystemMessage;
    @Bind(R.id.tv_run_order_number)
    TextView mTvRunOrderNumber;
    @Bind(R.id.tv_run_order_money)
    TextView mTvRunOrderMoney;
    @Bind(R.id.tv_system_message_title)
    TextView mTvSystemMessageTitle;
    @Bind(R.id.sv_rush_home)
    SpringView mSvRushHome;
    @Bind(R.id.ljd_rush_message)
    LJAdverView mLjdRushMessage;
    @Bind(R.id.tv_address_street)
    TextView mTvAddressStreet;
    @Bind(R.id.tv_rush_message)
    TextView mTvRushMessage;
    @Bind(R.id.rl_send_message)
    RelativeLayout mRlSendMessage;


    private Dialog mRushOrderDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_rush_single;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        inits();
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        mLlHomeRefresh.setVisibility(View.VISIBLE);
        mLlHomeVicinity.setVisibility(View.GONE);
        init();
    }

    private void inits() {

        if (AccountModel.getInstance().getRoleType().equals("run")) {
            mRlSendMessage.setVisibility(View.GONE);
        }
        getRunInfo();
        getBanner();
        getRunStatus();

    }

    private void init() {

        mSvRushHome.setType(SpringView.Type.FOLLOW);
        mSvRushHome.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                inits();
            }

            @Override
            public void onLoadmore() {

            }
        });
        mSvRushHome.setHeader(new HelperHeads(getActivity()));
    }

    /**
     * 获取接单状态
     */
    private void getRunStatus() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getRunStatues()
                .compose(RxHelper.<StatusEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<StatusEntity>() {
                    @Override
                    protected void onSucc(StatusEntity status) {
                        if (status.getNotice() == 1) {
                            getSystem();
                            getRushMessage();
                            mLjdRushMessage.setVisibility(View.VISIBLE);
                            mTvRushMessage.setVisibility(View.GONE);
                        } else if (status.getNotice() == 2) {
                            mTvSystemMessage.setText("");
                            mTvSystemMessageTitle.setText(getActivity().getResources().getString(R.string.rush_home_system_message));
                            mLjdRushMessage.stop();
                            mLjdRushMessage.setVisibility(View.GONE);
                            mTvRushMessage.setVisibility(View.VISIBLE);
                        }
                        mSvRushHome.onFinishFreshAndLoad();


                    }

                    @Override
                    protected void onFail(String msg) {
                        LogUtil.e(" 获取接单状态 " + msg);
                        ToastUtil.showToast(msg);
                        mSvRushHome.onFinishFreshAndLoad();
                    }
                }));
    }

    /**
     * 轮播图
     */
    public void getBanner() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getBanner(ROLE, MDConstant.PLATFORM)
                .compose(RxHelper.<ArrayList<BannerEntity>>defaultHandleResult())
                .subscribe(new RxSubscribe<ArrayList<BannerEntity>>() {
                    @Override
                    protected void onSucc(final ArrayList<BannerEntity> bannerEntities) {
                        List<String> imgs = new ArrayList<String>();
                        for (int i = 0; i < bannerEntities.size(); i++) {
                            String img = "http://www."+bannerEntities.get(i).getPath();
//                            String img = bannerEntities.get(i).getPath();
                            imgs.add(img);
                        }
                        mBannerRushCarousel.setData(imgs, null);
                        mBannerRushCarousel.setAdapter(new BGABanner.Adapter() {
                            @Override
                            public void fillBannerItem(BGABanner banner, View view, Object model, int position) {
                                Glide.with(getActivity()).load(model).into((ImageView) view);
                            }
                        });
                        mBannerRushCarousel.setOnItemClickListener(new BGABanner.OnItemClickListener() {
                            @Override
                            public void onBannerItemClick(BGABanner banner, View view, Object model, int position) {
                                UIHelper.showWeb(getActivity(), new WebViewEntity("", bannerEntities.get(position).getUrl()));
                            }
                        });
                    }

                    @Override
                    protected void onFail(String msg) {
                        LogUtil.e(" 轮播图 " + msg);
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    /**
     * 系统消息
     */
    private void getSystem() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getSystem().compose(RxHelper.<RunSystemMessage>defaultHandleResult())
                .subscribe(new RxSubscribe<RunSystemMessage>() {
                    @Override
                    protected void onSucc(RunSystemMessage runSystemMessage) {
                        mTvSystemMessage.setText(runSystemMessage.getContent());
                        mTvSystemMessageTitle.setText(runSystemMessage.getTitle());
                        mSvRushHome.onFinishFreshAndLoad();
                    }

                    @Override
                    protected void onFail(String msg) {
                        LogUtil.e(" 系统消息 " + msg);
                        ToastUtil.showToast(msg);
                        mSvRushHome.onFinishFreshAndLoad();
                    }
                }));
    }

    /**
     * 跑客消息
     */
    private void getRunInfo() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getRunInfo()
                .compose(RxHelper.<RunInfo>defaultHandleResult())
                .subscribe(new RxSubscribe<RunInfo>() {
                    @Override
                    protected void onSucc(RunInfo runInfo) {
                        LogUtil.e(runInfo.toString());
                        mTvRunOrderNumber.setText(runInfo.getOrder_num() + "");
                        mTvRunOrderMoney.setText("￥" + runInfo.getMoney());
                        mSvRushHome.onFinishFreshAndLoad();
                    }

                    @Override
                    protected void onFail(String msg) {
                        LogUtil.e(" 跑客消息 " + msg);
                        ToastUtil.showToast(msg);
                        mSvRushHome.onFinishFreshAndLoad();

                    }
                }));
    }

    @OnClick({R.id.ll_home_location, R.id.ll_home_refresh, R.id.tv_rush_order, R.id.tv_rush_vicinity_order})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_home_location:
//                UIHelper.showCity(getActivity());
                break;
            case R.id.ll_home_refresh:
                inits();
                break;
            case R.id.tv_rush_order:
                getRecentOrder();
                break;
            case R.id.tv_rush_vicinity_order:
                UIHelper.showRushVicinity(getActivity());
                break;
        }
    }

    public void RushOrderUI(final OrderEntity order) {
        mRushOrderDialog = new Dialog(getActivity(), R.style.dialog);
        mRushOrderDialog.setContentView(R.layout.dialog_rush_order_info);
        ImageView mIvDialogRushClose = (ImageView) mRushOrderDialog.findViewById(R.id.iv_dialog_rush_close);
        ImageView mIvOrderType = (ImageView) mRushOrderDialog.findViewById(R.id.iv_order_type);
        TextView mTvDistanceYou = (TextView) mRushOrderDialog.findViewById(R.id.tv_distance_you);
        TextView mTvOrderServiceMoney = (TextView) mRushOrderDialog.findViewById(R.id.tv_order_service_money);
        TextView mTvRawServiceMoney = (TextView) mRushOrderDialog.findViewById(R.id.tv_raw_service_money);
        TextView mTvAddServiceMoney = (TextView) mRushOrderDialog.findViewById(R.id.tv_add_service_money);
        TextView mTvOrderGoodsName = (TextView) mRushOrderDialog.findViewById(R.id.tv_order_goods_name);
        TextView mTvOrderAddressOne = (TextView) mRushOrderDialog.findViewById(R.id.tv_order_address_one);
        TextView mTvOrderAddressTwo = (TextView) mRushOrderDialog.findViewById(R.id.tv_order_address_two);
        TextView mTvOrderDistance = (TextView) mRushOrderDialog.findViewById(R.id.tv_order_distance);
        TextView mTvOrderTime = (TextView) mRushOrderDialog.findViewById(R.id.tv_order_time);
        TextView mTvOrderType = (TextView) mRushOrderDialog.findViewById(R.id.tv_order_type);
        TextView mTvRushOrderSubmit = (TextView) mRushOrderDialog.findViewById(R.id.tv_rush_order_submit);
        mTvOrderServiceMoney.setText(order.getServiceMoney());
        mTvDistanceYou.setText(order.getDistance() + "km");
        mTvOrderDistance.setText(order.getSendDistance() + "km");
        mTvOrderGoodsName.setText(order.getRemark());
        mTvAddServiceMoney.setText(order.getAddServiceMoney());
        mTvRawServiceMoney.setText("￥" + (Double.valueOf(order.getServiceMoney()) - Double.valueOf(order.getAddServiceMoney())) + "");
        mTvOrderTime.setText(getActivity().getResources().getString(R.string.rush_dialog_time,
                TimeUtils.milliseconds2String(Long.valueOf(order.getCreateTime()) * 1000)));
        mTvOrderAddressTwo.setText(order.getGetAddr());

        if (order.getBusType() == 1) {
            Glide.with(getActivity())
                    .load(R.drawable.iv_details_agecy)
                    .into(mIvOrderType);
            mTvOrderType.setText(getActivity().getResources().getString(R.string.send_home_agency));
            Drawable addressOne = getActivity().getResources().getDrawable(R.drawable.vicinity_order_class);
            addressOne.setBounds(0, 0, addressOne.getMinimumWidth(), addressOne.getMinimumHeight());
            mTvOrderAddressOne.setCompoundDrawables(addressOne, null, null, null);
            mTvOrderAddressOne.setText(order.getHandleType());
        } else if (order.getBusType() == 2) {
            Glide.with(getActivity())
                    .load(R.drawable.iv_details_minnetonka)
                    .into(mIvOrderType);
            mTvOrderType.setText(getActivity().getResources().getString(R.string.send_home_minnetonka));
            Drawable addressOne = getActivity().getResources().getDrawable(R.drawable.vicinity_order_shop);
            addressOne.setBounds(0, 0, addressOne.getMinimumWidth(), addressOne.getMinimumHeight());
            mTvOrderAddressOne.setCompoundDrawables(addressOne, null, null, null);
            mTvOrderAddressOne.setText(order.getPostAddr());
        } else if (order.getBusType() == 3) {
            Glide.with(getActivity())
                    .load(R.drawable.iv_details_take)
                    .into(mIvOrderType);
            mTvOrderType.setText(getActivity().getResources().getString(R.string.send_home_take));

            Drawable addressOne = getActivity().getResources().getDrawable(R.mipmap.vicinity_order_take);
            addressOne.setBounds(0, 0, addressOne.getMinimumWidth(), addressOne.getMinimumHeight());
            mTvOrderAddressOne.setCompoundDrawables(addressOne, null, null, null);
            mTvOrderAddressOne.setText(order.getPostAddr());
        }


        mIvDialogRushClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRushOrderDialog.dismiss();
            }
        });
        mTvRushOrderSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rushOrder(order.getId() + "");
                mRushOrderDialog.dismiss();
            }
        });


        mRushOrderDialog.show();
    }

    private void getRecentOrder() {
        startLoadingDialog(true);
        addSubscribe(DataManager.getInstance().getUserApi()
                .getRecentOrder(AppModel.getInstance().getAppLocationEntity().getLats(),
                        AppModel.getInstance().getAppLocationEntity().getLongs())
                .compose(RxHelper.<OrderEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<OrderEntity>() {
                    @Override
                    protected void onSucc(OrderEntity orderEntity) {
                        stopLoadingDialog();
                        RushOrderUI(orderEntity);
                    }

                    @Override
                    protected void onFail(String msg) {
                        LogUtil.e("getRecentOrder " + msg +AppModel.getInstance().getAppLocationEntity().getLats()+":"+AppModel.getInstance().getAppLocationEntity().getLongs());
                        stopLoadingDialog();
                        ToastUtil.showToast(msg);
                    }
                }));
    }


    private void rushOrder(final String busId) {
        addSubscribe(DataManager.getInstance().getUserApi()
                .rusnOrder(busId)
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        UIHelper.showRushOrderDetails(getActivity(), busId);
                    }

                    @Override
                    protected void onFail(String msg) {
                        LogUtil.e("rushOrder " + msg);
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    private void getRushMessage() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getRushMessageInfo("1")
                .compose(RxHelper.<ArrayList<MessageEntity>>defaultHandleResult())
                .subscribe(new RxSubscribe<ArrayList<MessageEntity>>() {
                    @Override
                    protected void onSucc(ArrayList<MessageEntity> messageEntities) {
                        LJViewAdapter ljViewAdapter = new LJViewAdapter(messageEntities);
                        mLjdRushMessage.setAdapter(ljViewAdapter);
                        mLjdRushMessage.start();
                    }

                    @Override
                    protected void onFail(String msg) {
                        if (msg.equals("0") || msg.equals("success")) {
                            mTvRushMessage.setVisibility(View.VISIBLE);
                            mLjdRushMessage.setVisibility(View.GONE);
                            mTvRushMessage.setText("当前没有跑客通知消息");
                        } else {
                            LogUtil.e("getRushMessage " + msg);
                            ToastUtil.showToast(msg);
                        }

                    }
                }));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LocationEvent locationEvent) {
        if (locationEvent.getStart().equals("0")) {
            mTvRushOrder.setEnabled(true);
            mTvRushVicinityOrder.setEnabled(true);
            mTvAddressStreet.setText(AppModel.getInstance().getAppLocationEntity().getStreet());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CityEvnet cityEvnet) {
        mTvAddressStreet.setText(cityEvnet.getCityName());
    }


}
